<template>
  <div class="app-container">
    <!-- 头部搜索框 -->
    <div class="filter-container">
      <section class="sectin01">
        <el-button
          v-popover:popover4
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          >新增教程</el-button
        >
        <el-button
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="addIndex"
          >新增目录</el-button
        >
      </section>
    </div>
    <!--新增教程 弹框 -->
    <el-popover ref="popover4" placement="bottom" trigger="click">
      <div class="aa">
        <el-form
          label-width="120px"
          ref="form_change"
          :model="course"
          :rules="rules"
        >
          <el-form-item label="标题" prop="title">
            <el-input style="width: 30%" v-model="course.title"></el-input>
          </el-form-item>
          <el-form-item label="目录" prop="catalogue_id">
            <el-select
              style="width: 30%"
              clearable
              v-model="course.catalogue_id"
              placeholder="目录"
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item, index) in index_lists || []"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="序号" prop="sequence">
            <el-input style="width: 30%" v-model="course.sequence"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-upload
              class="avatar-uploader"
              action
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadFile"
              :data="getDatas"
            >
              <el-button type="primary" size="mini">点击上传图片</el-button>
            </el-upload>
            <quill-editor
              ref="myQuillEditor"
              style="height: 380px"
              v-model="course.content"
              class="myQuillEditor"
              :options="editorOption"
            />
          </el-form-item>
        </el-form>
        <div>
          <el-button
            class="add_course"
            type="primary"
            size="small"
            @click="addCourse"
            >添加教程</el-button
          >
        </div>
      </div>
    </el-popover>

    <!-- 添加目录弹框 -->
    <el-dialog
      :visible.sync="addIndexs"
      width="450px"
      title="新增目录"
      class="dialog_edit"
      center
    >
      <el-form label-width="120px" ref="add_Index" :model="addindex_value">
        <el-form-item label="目录名称">
          <el-input
            style="width: 200px"
            v-model="addindex_value.name"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="addIndexs = false">取 消</el-button>
          <el-button class="confirm" type="primary" @click="edit01"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 内容 -->
    <div class="content">
      <el-table
        :key="tableKey"
        v-loading="listLoading01"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.6)"
        :data="courseList"
        max-height="700"
        border
        style="width: 80%"
        highlight-current-row
        :row-class-name="tableRowClassName"
        :default-sort="{ prop: 'last_use_time', order: 'descending' }"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          min-width="20"
        ></el-table-column>

        <el-table-column
          label="标题"
          min-width="50"
          class-name="end_times"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.title || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="目录结构"
          min-width="50"
          class-name="end_times"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.catalogue_name || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="序号"
          min-width="50"
          class-name="end_times"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.sequence || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="内容"
          min-width="50"
          class-name="end_times"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            <span>{{ row.content || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="添加时间"
          min-width="50"
          sortable
          prop="last_use_time"
          class-name="end_times"
          align="center"
        >
          <template slot-scope="{ row }">
            <span>{{ row.last_use_time || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="100"
          class-name="end_times"
          align="center"
        >
          <template slot-scope="{ row }">
            <el-button
              style="margin-left: 10px"
              size="mini"
              plain
              type="info"
              @click="detailCourse(row.id)"
              >详情</el-button
            >
            <el-button
              style="margin-left: 10px"
              size="mini"
              plain
              type="primary"
              @click="edit02(row.id)"
              >编辑</el-button
            >

            <el-button
              style="margin-left: 10px"
              size="mini"
              plain
              type="danger"
              @click="deletes(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑弹框 -->
      <el-dialog
        title="编辑教程"
        :visible.sync="dialog_edit"
        v-show="dialog_edit"
        fullscreen
        center
      >
        <div class="aa">
          <el-form
            label-width="80px"
            ref="form_change"
            :model="detail"
            :rules="rules"
          >
            <el-form-item label="标题" prop="title">
              <el-input style="width: 30%" v-model="detail.title"></el-input>
            </el-form-item>
            <el-form-item label="目录" prop="catalogue_id">
              <el-select
                style="width: 30%"
                clearable
                v-model="detail.catalogue_id"
                placeholder="目录"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in index_lists || []"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序号" prop="sequence">
              <el-input style="width: 30%" v-model="detail.sequence"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-upload
                class="avatar-uploader"
                action
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadFile"
                :data="getDatas"
              >
                <el-button size="mini" type="primary">点击上传图片</el-button>
              </el-upload>
              <!-- <img :src="baseUrl" alt=""> -->
              <quill-editor
                style="height: 700px"
                v-model="detail.content"
                class="myQuillEditor"
                :options="editorOption"
                ref="myQuillEditor"
              />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog_edit = false">取 消</el-button>
          <el-button type="primary" @click="edit03">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="right01" @click="view_course">查看<br />教程</div>
    <div class="view_course" v-if="viewCourse == true">
      <div class="content">
        <section>
          <el-button
            class="confirm"
            style="width: 100px"
            @click="viewCourse = false"
            >学习教程</el-button
          >
        </section>
        <section style="margin-top: 10px">
          <el-button style="width: 100px" class="confirm" @click="router02"
            >目录</el-button
          >
        </section>
        <section style="margin-top: 10px" v-if="index_show == true">
          <div
            class="parent"
            style="max-height: 700px; background: #fff; overflow: hidden"
          >
            <div
              class="chilter"
              style="max-height: 700px; background: #fff; overflow-y: scroll"
            >
              <el-tree
                :props="customProps"
                :data="index_list"
                @node-click="check"
                default-expand-all
                :expand-on-click-node="false"
                node-key="id"
                ref="authTree"
              >
              </el-tree>
            </div>
          </div>
        </section>
        <section v-if="detail_show">
          <el-header class="headers">{{ detail_course.title || "" }}</el-header>
          <div
            class="parent"
            style="height: 600px; background: #fff; overflow: hidden"
          >
            <div
              class="chilter"
              style="height: 600px; background: #fff; overflow-y: scroll"
            >
              <section
                class="ql-editor"
                v-html="detail_course.content || ''"
              ></section>
            </div>
          </div>
          <img src="" style="display: inline-block" alt="" />
          <div class="footer">
            <el-button
              style="width: 100px"
              class="confirm"
              @click="changePage(0)"
              >上一页</el-button
            >
            <el-button
              style="width: 100px"
              class="confirm"
              @click="changePage(1)"
              >下一页</el-button
            >
          </div>
        </section>
      </div>
    </div>
  </div>
</template>

<script>
//引入vuex
import axios from "axios";
import { mapState } from "vuex";
// import "quill/dist/quill.core.css";
// import "quill/dist/quill.snow.css";
// import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
const Qs = require("qs");
import {
  getContentInfo_manage,
  deleteTutorials_manage,
  dinsertCatalogue_manage,
  insertToturial_manage,
  getCatalogue_manage,
  editTutorials_manage,
  getDetailsTutorial_manage,
  getTutorialList_manage,
  nextTutorial_manage,
  upload_card,
} from "@/api/manage";
import toolbarOptions from "@/utils/toolbarOptions.js";
export default {
  name: "ComplexTable",
  filters: {
    filterLongTime(status = "") {
      var str = status;
      str = str.replace(/\d{2}:\d{2}:\d{2}/g, "");
      return str;
    },
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    masDateFormat: function (msg = "", pattern = "") {
      var mt = new Date(msg);
      var y = mt.getFullYear();
      var m = (mt.getMonth() + 1).toString().padStart(2, "0");
      var d = mt.getDate();
      if (pattern == "yyyy-mm-dd") {
        return y + "-" + m + "-" + d;
      }
      return y + "-" + m + "-" + d;
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  computed: {
    ...mapState(["manages"]),
  },
  components: {
    quillEditor,
  },
  data() {
    return {
      baseUrl: "",
      getDatas: {
        user: localStorage.username,
        sid: localStorage.sid,
      },
      getHeaders: {
        Accept: "application/json",
      },
      serverUrl: "http://cs.api.imp.com/uploads/",
      customProps: {
        label: "name",
        children: "content",
      },
      page_id: "",
      index_show: true,
      index_lists: [{}],
      viewCourse: false,
      detail: {},
      courseList: [],
      value7: [""],
      tableKey: 0,
      listLoading01: false,

      editorOption: {
        placeholder: "",
        theme: "snow",
        modules: {
          toolbar: {
            container: toolbarOptions,
          },
        },
      },
      addIndexs: false,
      dialog_edit: false,
      detail_show: false,
      courses_id: "",
      detail_course: [{}],
      addindex_value: { name: "" },
      index_list: [{}],
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        catalogue_id: [
          { required: true, message: "请输入目录", trigger: "blur" },
        ],
        sequence: [{ required: true, message: "请输入序号", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
      course: {
        title: "",
        catalogue_id: "",
        sequence: "",
        content: "",
      },
      course_clear: {
        title: "",
        catalogue_id: "",
        sequence: "",
        content: "",
      },
    };
  },
  created() {
    // console.log(toolbarOptions);
    this.getContentInfo_manage(); //ip订单支出表
    this.getCatalogue_manage();
  },
  methods: {
    handleAvatarSuccess() {},
    beforeAvatarUpload() {},
    uploadFile(item) {
      let form = new FormData();
      form.append("upload", item.file);
      form.append("user", localStorage.username);
      form.append("sid", localStorage.sid);
      axios.defaults.headers.post["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
      axios({
        method: "post",
        data: form,
        transformRequest: [
          function () {
            return form;
          },
        ],
        url: process.env.VUE_APP_BASE_API + "apiman/tutorial/uploadImage",
      }).then((res) => {
        if (res.data.status == 0) {
          this.$message({
            type: "success",
            message: res.data.msg,
          })
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
          });
          
        }
        let quill = this.$refs.myQuillEditor.quill;
        console.log(res.data.info);
        quill.focus();
        let length = quill.getSelection().index;
        quill.insertEmbed(length, "image", res.data.info);
        quill.setSelection(length + 1);
      });
    },
    changePage(page) {
      nextTutorial_manage({ status: page, id: this.page_id }).then((res) => {
        if (res.status == 1) {
          this.$message({
            type: "warning",
            message: res.msg,
            customClass: "zZindex",
          });
        } else {
          this.detail_course = res.data[0];
          this.page_id = res.data[0].id;
        }
      });
    },
    check(data, node) {
      this.detail_course = [{}];
      this.page_id = data.id;
      getDetailsTutorial_manage({ id: data.id }).then((res) => {
        if (res.status == 0) {
          if (!res.data[0]) {
            this.detail_course = [{}];
            return false;
          }
          this.detail_course = res.data[0];
          this.index_show = false;
          this.detail_show = true;
        }
      });
      // console.log(this.detail_course);
    },
    router02() {
      this.index_show = true;
      this.detail_show = false;
    },
    view_course() {
      this.viewCourse = true;
      getTutorialList_manage().then((res) => {
        this.index_list = res.data.list;
        console.log(this.index_list);
        for (var i = 0; i < this.index_list.length; i++) {
          for (var j = 0; j < this.index_list[i].content.length; j++) {
            this.index_list[i].content[j].name = this.index_list[i].content[
              j
            ].title;
          }
        }
      });
    },
    edit03() {
      editTutorials_manage({
        id: this.courses_id,
        title: this.detail.title,
        catalogue_id: this.detail.catalogue_id,
        sequence: this.detail.sequence,
        content: this.detail.content,
      }).then((res) => {
        // console.log(res);
        if (res.status == 0) {
          this.$message({
            type: "success",
            message: res.msg,
          });
          this.getContentInfo_manage();
          this.dialog_edit = false;
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    edit02(id) {
      // this.$router.push({
      //   path:`editCourse/${id}`
      // })
      this.dialog_edit = true;
      this.courses_id = id;
      getDetailsTutorial_manage({ id }).then((res) => {
        this.detail = res.data[0];
      });
    },
    //指定多少天后,获取时间
    get_time() {
      let mm =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let yy =
        new Date().getFullYear() < 10
          ? "0" + new Date().getFullYear()
          : new Date().getFullYear();
      let dd = new Date().getDate()
        ? "0" + new Date().getDate()
        : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      var value =
        yy + "-" + mm + "-" + dd + " " + "00" + ":" + "00" + ":" + "00 ";
      var value01 =
        yy + "-" + mm + "-" + dd + " " + "23" + ":" + "59" + ":" + "59 ";
      return [value, value01];
    },

    GetDateStr(AddDayCount) {
      var dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
      var y = dd.getFullYear();
      var m =
        dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1; //获取当前月份的日期，不足10补0
      var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号，不足10补0
      // console.log(y + "-" + m + "-" + d)
      return y + "-" + m + "-" + d + " " + "00" + ":" + "00" + ":" + "00 ";
    },
    // 请求接口方法
    getContentInfo_manage() {
      this.listLoading01 = true;
      getContentInfo_manage({}).then((res) => {
        this.courseList = res.data.list || [{}];
        this.listLoading01 = false;
      });
    },
    getCatalogue_manage() {
      getCatalogue_manage({}).then((res) => {
        // console.log(res);
        this.index_lists = res.data.list;
      });
    },
    addCourse() {
      this.$refs["form_change"].validate((valid) => {
        if (valid) {
          this.$confirm("确认该操作吗?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              // console.log(id);
              insertToturial_manage({
                title: this.course.title,
                catalogue_id: this.course.catalogue_id,
                sequence: this.course.sequence,
                content: this.course.content,
              }).then((res) => {
                // this.getData_card();
                if (res.status == 0) {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.getContentInfo_manage();
                  this.course = this.course_clear;
                } else {
                  this.$message({
                    type: "error",
                    message: res.msg,
                  });
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "取消操作",
              });
            });
        }
      });
    },
    time02() {
      // console.log(this.value7)
      if (this.value7) {
        this.$store.commit("serchTime_card", this.value7);
      } else {
        this.$store.commit("serchTime_card", ["", ""]);
      }
    },
    deletes(id, name) {
      this.$confirm("确认该操作吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(id);
          deleteTutorials_manage({
            id: id,
          }).then((res) => {
            // this.getData_card();
            if (res.status == 0) {
              this.$message({
                type: "success",
                message: res.msg,
              });
              this.getContentInfo_manage();
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消操作",
          });
        });
    },
    addIndex() {
      this.addIndexs = true;
      this.$nextTick(() => {
        this.$refs["add_Index"].clearValidate();
      });
    },
    detailCourse(id) {
      this.$router.push({
        path: `detailCourse/${id}`,
      });
    },
    edit01() {
      this.$confirm("确认该操作吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // console.log(id);
          dinsertCatalogue_manage({
            name: this.addindex_value.name,
          }).then((res) => {
            // this.getData_card();
            if (res.status == 0) {
              this.$message({
                type: "success",
                message: res.msg,
              });
              this.getContentInfo_manage();
              this.getCatalogue_manage();
              this.addIndexs = false;
              this.addindex_value.name = "";
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消操作",
          });
        });
    },
    //行样式
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row";
      } else {
        return "success-row";
      }
    },
  },
};
</script>
<style lang='less' scope>
@variable: 120px;

/deep/.mce-content-body p img {
  max-width: 80%;
  width: auto;
  height: auto;
}
.footer {
  height: 50px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
}
.headers {
  font-family: "Microsoft YaHei";
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  line-height: 50px;
}
.main_detail {
  padding: 20px;
  display: flex;
}
.view_course {
  padding: 20px;
  top: 0%;
  left: 0;
  // right: 1%;
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  background-color: rgb(238, 238, 238);
  position: fixed;
  z-index: 4999;
}
.authTree {
  display: flex;
  padding: 20px;
  .item {
    flex: 1;
  }
  .custom-tree-node {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .label {
      font-size: 14px;
    }
    .add {
      color: #e6a23c;
    }
    .del {
      color: #f56c6c;
    }
  }
}
.right01 {
  z-index: 110;
  cursor: pointer;
  font-size: 26px;
  position: fixed;
  right: 5%;
  top: 15%;
  width: @variable;
  height: @variable;
  border-radius: 50%;
  background-color: rgb(154, 221, 241);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  font-weight: bold;
}
.aa {
  padding: 10px;
  .head {
    margin-bottom: 10px;
  }
}
.sectin01 {
  margin-top: 6px;
}
/deep/.el-table td {
  padding: 6px 0px;
}
.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
.addserve {
  /deep/.el-input {
    width: 80%;
    text-align: center;
    font-weight: bold;
    color: red;
  }
}

.success {
  color: #67c23a;
}
.warning {
  color: #e6a23c;
}
.outtime {
  color: #f56c6c;
}

/deep/.el-table .red_ip {
  color: #f56c6c !important;
}
.tables {
  background-color: pink;
  height: 80%;
}
/deep/.el-table {
  padding-bottom: 50px;
}
.app-container {
  padding-left: 10px;
  padding-top: 0px;
  // .content {
  //   .right {
  //     box-sizing: border-box;
  //     //   width: 45%;
  //     .center {
  //       display: flex;
  //       justify-content: space-between;
  //       .left,
  //       .right {
  //         box-sizing: border-box;
  //         width: 49%;
  //         //   height: 600px;
  //         padding: 5px;
  //         /deep/.el-input__inner {
  //           line-height: 27px;
  //           height: 27px;
  //         }
  //       }
  //     }
  //   }
  // }
}
/deep/.el-table {
  color: #000;
}
.add_course {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translate(-50%);
}
/deep/.ql-image {
  display: none;
}
</style>